<template>
  <div class="mycontract-wrapper">
    <div class="mycontract-content">
      <h3 class="title">
        <span class="line"></span>我的合同
      </h3>
      <div class="content">
        <screen-bar :tab-list="tabList" @changeState="changeState"></screen-bar>
        <p class="tips">
          <span class="impor">*</span>温馨提示：为保障您的合法权益，请及时签署电子合同
        </p>
        <div
          class="table-wrapper"
          :class="{'hidden':loading}"
          v-loading="loading"
          :element-loading-text="loadingText"
          element-loading-spinner="el-icon-loading"
        >
          <div class="tb-scroll">
            <el-table :data="accountList" :header-cell-style="rowClass" :cell-style="cellStyle">
              <el-table-column prop="biz_order" label="订单编号" width="350"></el-table-column>
              <el-table-column prop="style" label="商品信息">
                <template slot-scope="scope">
                  <div
                    v-if="scope.row.product_type == 1"
                    class="goOrderDetails"
                    @click="goOrderDetails(scope.row.order_id)"
                    title="查看代理商品详情"
                  >
                    <p v-show="scope.row.product_area">{{scope.row.product_area}}</p>
                    <p>
                      <span>{{scope.row.product_name}}</span>
                      <span v-show="scope.row.product_place">/{{scope.row.product_place}}</span>
                      <span v-show="scope.row.product_style">/{{scope.row.product_style}}</span>
                    </p>
                  </div>
                  <div
                    v-else
                    class="goOrderDetails"
                    @click="goOrderDetails(scope.row.order_id)"
                    title="查看代理商品详情"
                  >
                    <p>{{scope.row.furniturecategory_name}}</p>
                    <p>
                      <span>{{scope.row.title}}</span>
                      <span v-show="scope.row.style_name">/{{scope.row.style_name}}</span>
                      <span v-show="scope.row.material_name">/{{scope.row.material_name}}</span>
                    </p>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="supplier_name" label="优选商家" width="180"></el-table-column>
              <el-table-column prop="userable_amount" label="代理订金" width="180">
                <template
                  slot-scope="scope"
                >{{scope.row.agent_deposit ? scope.row.agent_deposit + '元' : '-'}}</template>
              </el-table-column>
              <el-table-column prop="msg" label="签署时间" width="200">
                <template slot-scope="scope">{{scope.row.sign_time | parseTime}}</template>
              </el-table-column>
              <el-table-column prop="msg" label="合同状态" width="130">
                <template slot-scope="scope">
                  <span
                    :class="{'not-sign':scope.row.status != 2}"
                  >{{scope.row.status == 2 ? '已签署' : '未签署'}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="msg" label="操作" width="130">
                <template slot-scope="scope">
                  <p v-if="scope.row.contract_id">
                    <!-- 查看合同 -->
                    <span class="check-col" @click="_previewContract(scope.row.contract_id)">查看合同</span>
                  </p>
                  <p v-if=" scope.row.status == 2 && scope.row.contract_id">
                    <!-- 下载已签署合同 -->
                    <span class="check-col" @click="_downloadContract(scope.row.contract_id)">下载合同</span>
                  </p>
                  <!-- <p v-if="scope.row.status == 0 || scope.row.status == 1">
                  <a
                    class="sign-col"
                    href="javascript:;"
                    @click="_doCreate(scope.row.order_id)"
                  >立即签署</a>
                  </p>-->
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <el-pagination
          background
          layout="prev, pager, next, total, jumper"
          :page-size="listParams.limit"
          :total="paginationQuery.total"
          :current-page="listParams.p"
          @current-change="currentChange"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
import ScreenBar from "@/components/ScreenBar/ScreenBar";
import {
  getContractList,
  doCreate,
  doSign,
  downloadContract,
  previewContract,
} from "@/api/mycontract";
import { mapGetters } from "vuex";
const LIMIT = 8;
export default {
  name: "mycontract",
  computed: {
    ...mapGetters(["memberInfo"]),
  },
  data() {
    return {
      tabList: [
        { keyword: "全部", count: 0 },
        { keyword: "已签署", count: 0 },
        { keyword: "未签署", count: 0 },
      ],
      accountList: [],
      accountState: [],
      paginationQuery: {
        total: 0,
      },
      listParams: {
        p: 1,
        limit: LIMIT,
        type: 0,
      },
      loading: false,
      loadingText: "",
    };
  },
  created() {
    console.log("是否代理商", this.memberInfo.status);
    if (this.memberInfo.status == 1) {
      this._getContractList();
    } else {
      if (this.memberInfo.is_auth == 1) {
        this.$message.error("您还没加入云木屋代理，正在为您跳转");
        setTimeout(() => {
          this.$router.push({ name: "contractServices" });
        }, 1000);
      } else {
        this.$message.error("您还没有完成实名认证，正在为您跳转");
        setTimeout(() => {
          this.$router.push({ name: "explain" });
        }, 1000);
      }
    }
  },
  methods: {
    // 去商品详情
    goOrderDetails(id) {
      this.$router.push({
        name: "myagencydetail",
        params: { id: id },
      });
    },
    // 查看合同
    _previewContract(id) {
      this.loading = true;
      this.loadingText = "生成合同中";
      let params = {
        contract_id: id,
      };
      previewContract(params)
        .then((res) => {
          console.log(res);
          if (res.code == 1 && res.data.url) {
            window.open(res.data.url);
            console.log(res.data.url);
          } else {
            this.$message.error(res.msg || "请求失败");
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 下载合同
    _downloadContract(id) {
      this.loading = true;
      this.loadingText = "生成合同中";
      let params = {
        contract_id: id,
      };
      downloadContract(params)
        .then((res) => {
          console.log("下载合同res", res);
          let blob = new Blob([res], { type: "application/pdf" });
          let objectUrl = window.URL.createObjectURL(blob);
          const fname = "代理合同";
          const contractLink = document.createElement("a");
          contractLink.style.display = "none";
          contractLink.href = objectUrl;
          contractLink.setAttribute("download", fname);
          document.body.appendChild(contractLink);
          contractLink.click();
          window.URL.revokeObjectURL(contractLink.href); // 释放URL 对象
          document.body.removeChild(contractLink);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    _getContractList() {
      this.loading = true;
      this.loadingText = "拼命加载中";
      getContractList(this.listParams)
        .then((res) => {
          this.accountList = res.data.list || [];
          this.accountState = res.data.statistics || [];
          this.paginationQuery.total = +res.data.total || 0;
          this.initTabCount();
          console.log("表格数据", this.accountList);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    _doCreate(id) {
      this.loading = true;
      this.loadingText = "生成合同中";
      doCreate({ order_id: id })
        .then((res) => {
          this.$confirm("合同生成成功，确认签署合同?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.loading = true;
              this.loadingText = "合同签署中";
              doSign({ order_id: id })
                .then((res) => {
                  this.$message({
                    type: "success",
                    message: "合同签署成功",
                  });
                  this._getContractList();
                })
                .finally(() => {
                  this.loading = false;
                });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消签署",
              });
              this._getContractList();
            });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    _doCheck(id) {
      this.loading = true;
      this.loadingText = "生成合同中";
      doCreate({ order_id: id })
        .then((res) => {
          window.open(res.data.contract_url);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    currentChange(index) {
      this.listParams.p = index;
      this._getContractList();
    },
    changeState(type) {
      this.listParams.type = type;
      this.listParams.p = 1;
      this._getContractList();
    },
    initTabCount() {
      let list = this.accountState;
      this.tabList.filter((item, index) => {
        item.count = list[index] || 0;
      });
    },
    rowClass() {
      return "background:rgba(240,249,252,1);font-size:14px;color:#999;font-weight:400;text-align:center;height:40px;padding: 0;";
    },
    cellStyle() {
      return "height:60px;font-size:14px;color:#333;text-align:center;";
    },
  },
  components: {
    ScreenBar,
  },
};
</script>
<style lang="scss" scoped>
.mycontract-wrapper {
  width: 100%;
  height: 100%;
  padding: 20px;
  display: flex;
  flex-direction: column;
  overflow: auto;
  padding-bottom: 0;
  .mycontract-content{
    min-width: 1400px;
  }
  .title {
    font-size: 18px;
    color: #333;
    font-weight: bold;
    height: 54px;
    line-height: 54px;
    padding: 0 20px;
    background: #fff;
    margin: 0 0 5px 0;
    .line {
      display: inline-block;
      width: 3px;
      height: 18px;
      background: #fe6616;
      border-radius: 2px;
      margin: 0 10px -2px 0;
    }
  }
  .content {
    padding: 0 60px;
    background: #fff;
    padding-bottom: 20px;
    border-radius: 2px;
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    .tips {
      font-size: 12px;
      color: #999;
      margin-bottom: 2px;
      .impor {
        color: #f76060;
      }
    }
    .table-wrapper {
      flex: 1;
      overflow: hidden;
      min-height: 608px;
      p {
        margin: 0;
        &:nth-child(2) {
          margin-top: 4px;
        }
      }
      .not-sign {
        color: #f76060;
      }
      .check-col {
        color: #999;
        cursor: pointer;
        &:hover {
          color: #fe681c;
        }
      }
      .sign-col {
        color: #666;
        &:hover {
          color: #fe681c;
        }
      }
    }
    .el-pagination {
      text-align: right;
      margin-top: 20px;
    }
  }
  .goOrderDetails {
    cursor: pointer;
    &:hover {
      color: #fe681c;
    }
  }
}
</style>
